package cn.remex.contrib.service;

import cn.remex.RemexConstants;
import cn.remex.contrib.appbeans.DataCvo;
import cn.remex.contrib.appbeans.DataRvo;
import cn.remex.core.exception.ServiceCode;
import cn.remex.core.util.Judgment;
import cn.remex.db.Database;
import cn.remex.db.DbCvo;
import cn.remex.db.rsql.RsqlConstants;
import cn.remex.mongo.MongoManager;
import cn.remex.web.service.BsRvo;
import cn.remex.web.service.BusinessService;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.remex.mongo.MongoModel.SysMongoCollection.SysLog;

/**
 * @author  GQY
 * @since 2016/1/5.
 */
@BusinessService
public class DataService {


    @BusinessService
    public BsRvo list(DataCvo bsCvo, String modelName) {
        Class clazz = Database.getSession().obtainModelClass(modelName);
        DbCvo ret = bsCvo.obtainDbCvo(clazz);
        return new DataRvo(ret.ready().query(), RsqlConstants.DataFormatType.MapTree);
    }


    @BusinessService(bodyParamName = "dicsRequest", cachedArgIndexs = {0})
    public BsRvo dics(String dicsRequest, List<DataCvo> dicCvos) {
        List<List<?>> dics = new ArrayList<>();
        //按顺序返回dics
        dicCvos.forEach(dicCvo -> dics.add(dicCvo.obtainDbCvo().ready().query().getMapRows()));
        return new BsRvo(ServiceCode.SUCCESS, "OK", dics);
    }

    //!!!!!!!!!!!!!!!!!!!!!!警告!!!!!!!!!!!!!!!!!!!!!!!!!!!!//
    //DataService 是一个特殊的用于数据库操作的服务，里面的所有方法均会以/smvc/DataService/methodName/(param)的形式对外暴露。请不要将业务方法或特定的一类方法放到这里。
    //可以参考AuthenticateBtx.obtainDefaultUris();

    @BusinessService(bodyParamName = "logJson")
    public void logToMongo(String type, String logJson) {
        RemexConstants.logger.warn("记录日志错误:type={}; logJson={}", type, logJson);
        if (!Judgment.nullOrBlank(type) && !Judgment.nullOrBlank(logJson)) {
            try{
                MongoManager.collection(SysLog).insertOne(new Document("type", type).append("data", Document.parse(logJson)).append("updateTime", new Date()));
            }catch (Exception e){
                RemexConstants.logger.warn("记录日志错误", e);
            }
        }

    }

}
